package co.yixiang.modules.shop.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.exception.ErrorRequestException;
import co.yixiang.modules.activity.mapper.YxStoreBargainMapper;
import co.yixiang.modules.activity.mapper.YxStoreCombinationMapper;
import co.yixiang.modules.activity.mapper.YxStoreSeckillMapper;
import co.yixiang.modules.activity.service.YxStoreBargainService;
import co.yixiang.modules.activity.service.YxStoreCombinationService;
import co.yixiang.modules.activity.service.YxStoreSeckillService;
import co.yixiang.modules.order.service.YxStoreOrderService;
import co.yixiang.modules.shop.entity.YxInvestCart;
import co.yixiang.modules.shop.entity.YxSales;
import co.yixiang.modules.shop.entity.YxStoreCart;
import co.yixiang.modules.shop.entity.YxStoreProductAttrValue;
import co.yixiang.modules.shop.mapper.YxInvestCartMapper;
import co.yixiang.modules.shop.mapper.YxStoreCartMapper;
import co.yixiang.modules.shop.mapping.CartMap;
import co.yixiang.modules.shop.mapping.InvestCartMap;
import co.yixiang.modules.shop.service.YxInvestCartService;
import co.yixiang.modules.shop.service.YxSalesService;
import co.yixiang.modules.shop.service.YxStoreProductAttrService;
import co.yixiang.modules.shop.service.YxStoreProductService;
import co.yixiang.modules.shop.web.param.YxInvestCartQueryParam;
import co.yixiang.modules.shop.web.vo.YxInvestCartQueryVo;
import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.common.web.vo.Paging;
import co.yixiang.modules.shop.web.vo.YxInvestOrderQueryVo;
import co.yixiang.modules.shop.web.vo.YxStoreCartQueryVo;
import co.yixiang.modules.shop.web.vo.YxStoreProductQueryVo;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.utils.OrderUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.io.Serializable;
import java.util.*;


/**
 * <p>
 * 选购购物车表 服务实现类
 * </p>
 *
 * @author hisen
 * @since 2020-06-10
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class YxInvestCartServiceImpl extends BaseServiceImpl<YxInvestCartMapper, YxInvestCart> implements YxInvestCartService {


    @Autowired
    private YxInvestCartMapper yxInvestCartMapper;

    @Autowired
    private YxStoreProductService productService;
    @Autowired
    private YxStoreProductAttrService productAttrService;

    @Autowired
    private YxStoreOrderService storeOrderService;
    @Autowired
    private YxSalesService yxSalesService;

    @Autowired
    private InvestCartMap investCartMap;

    /**
     * 删除购物车
     *
     * @param uid
     * @param ids
     */
    @Override
    public void removeUserCart(int uid, List<String> ids) {
        QueryWrapper<YxInvestCart> wrapper = new QueryWrapper<>();
        wrapper.eq("sid", uid).in("id", ids);

        YxInvestCart yxInvestCart = new YxInvestCart();
        yxInvestCart.setIsDel(1);

        yxInvestCartMapper.update(yxInvestCart, wrapper);
    }

    /**
     * 清空购物车
     *
     * @param uid
     */
    @Override
    public void clearUserCart(int uid) {
        QueryWrapper<YxInvestCart> wrapper = new QueryWrapper<>();
        wrapper.eq("sid", uid);
        YxInvestCart yxInvestCart = new YxInvestCart();
        yxInvestCart.setIsDel(1);
        yxInvestCartMapper.update(yxInvestCart, wrapper);
    }

    /**
     * 改购物车数量
     *
     * @param cartId
     * @param cartNum
     * @param uid
     */
    @Override
    public void changeUserCartNum(int cartId, int cartNum, int uid) {
        QueryWrapper<YxInvestCart> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", uid).eq("id", cartId);

        YxInvestCart cart = getOne(wrapper);
        if (ObjectUtil.isNull(cart)) {
            throw new ErrorRequestException("购物车不存在");
        }

        if (cartNum <= 0) {
            throw new ErrorRequestException("库存错误");
        }

        //todo 普通商品库存
        int stock = productService.getProductStock(cart.getProductId()
                , cart.getProductAttrUnique());
        if (stock < cartNum) {
            throw new ErrorRequestException("该产品库存不足" + cartNum);
        }

        if (cartNum == cart.getCartNum()) return;

        YxInvestCart yxInvestCart = new YxInvestCart();
        yxInvestCart.setCartNum(cartNum);
        yxInvestCart.setId(Long.valueOf(cartId));
        yxInvestCartMapper.updateById(yxInvestCart);

    }

    /**
     * 购物车列表
     *
     * @param uid     用户id
     * @param cartIds 购物车id，多个逗号隔开
     * @param status  0-购购物车列表
     * @return
     */
    @Override
    public Map<String, Object> getUserProductCartList(int uid, String cartIds, int status) {
        QueryWrapper<YxInvestCart> wrapper = new QueryWrapper<>();
        wrapper.eq("sid", uid).eq("type", "product").eq("is_pay", 0)
                .eq("is_del", 0).orderByDesc("add_time");
        if (status == 0) wrapper.eq("is_new", 0);
        if (StrUtil.isNotEmpty(cartIds)) wrapper.in("id", Arrays.asList(cartIds.split(",")));
        List<YxInvestCart> carts = yxInvestCartMapper.selectList(wrapper);

        List<YxInvestCartQueryVo> valid = new ArrayList<>();
        List<YxInvestCartQueryVo> invalid = new ArrayList<>();

        for (YxInvestCart yxInvestCart : carts) {
            YxStoreProductQueryVo storeProduct = null;
            //必须得重新克隆创建一个新对象
            storeProduct = ObjectUtil.clone(productService
                    .getNewStoreProductById(yxInvestCart.getProductId()));


            YxInvestCartQueryVo yxInvestCartQueryVo = investCartMap.toDto(yxInvestCart);
            if (ObjectUtil.isNull(storeProduct)||storeProduct.getIsInvestOn() == 0) {
                YxStoreCart yxStoreCart = new YxStoreCart();
                yxStoreCart.setIsDel(1);
                yxInvestCartMapper.update(yxInvestCart,
                        new QueryWrapper<YxInvestCart>()
                                .lambda().eq(YxInvestCart::getId, yxInvestCart.getId()));
            }  else {
                    yxInvestCartQueryVo.setInvestPrice(storeProduct.getInvestPrice()
                            .doubleValue());

                  yxInvestCartQueryVo.setProductInfo(storeProduct);
                    valid.add(yxInvestCartQueryVo);

            }

        }

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("valid", valid);
        map.put("invalid", invalid);
        return map;
    }

    /**
     * 添加购物车
     *
     * @param sid               用户id
     * @param productId         普通产品编号
     * @param cartNum           购物车数量
     * @param productAttrUnique 属性唯一值
     * @param type              product
     * @param isNew             1 加入购物车直接购买  0 加入购物车
     * @return
     */
    @Override
    public int addCart(int sid, int productId, int cartNum, String productAttrUnique,
                       String type, int isNew) {

        YxStoreProductQueryVo productQueryVo = productService
                .getYxStoreProductById(productId);
        if (ObjectUtil.isNull(productQueryVo)) {
            throw new ErrorRequestException("该产品已下架或删除");
        }

//        int stock = productService.getProductStock(productId, productAttrUnique);
//        if (stock < cartNum) {
//            throw new ErrorRequestException("该产品库存不足" + cartNum);
//        }


        QueryWrapper<YxInvestCart> wrapper = new QueryWrapper<>();
        wrapper.eq("sid", sid).eq("type", type).eq("is_pay", 0).eq("is_del", 0).eq("product_id", productId)
                .eq("is_new", isNew).eq("product_attr_unique", productAttrUnique)
                .orderByDesc("id").last("limit 1");


        YxInvestCart cart = yxInvestCartMapper.selectOne(wrapper);
        YxInvestCart storeCart = new YxInvestCart();
        storeCart.setCartNum(cartNum);
        storeCart.setProductAttrUnique(productAttrUnique);
        storeCart.setProductId(productId);
        storeCart.setType(type);
        storeCart.setSid(sid);
        storeCart.setIsNew(isNew);
        if (ObjectUtil.isNotNull(cart)) {
            if (isNew == 0) {
                storeCart.setCartNum(cartNum + cart.getCartNum());
            }
            storeCart.setId(cart.getId());
            yxInvestCartMapper.updateById(storeCart);
        } else {
            //判断是否已经添加过
            storeCart.setAddTime(OrderUtil.getSecondTimestampTwo());
            yxInvestCartMapper.insert(storeCart);
        }

        return storeCart.getId().intValue();
    }

    @Override
    public int getUserCartNum(int sid, String type, int numType) {
        int num = 0;
        QueryWrapper<YxInvestCart> wrapper = new QueryWrapper<>();
        wrapper.eq("sid", sid).eq("type", type).eq("is_pay", 0).eq("is_del", 0);
        if (numType > 0) {
            num = yxInvestCartMapper.selectCount(wrapper);
        } else {
            num = yxInvestCartMapper.cartSum(sid, type);
        }
        return num;
    }

    @Override
    public YxInvestCartQueryVo getYxStoreCartById(Serializable id) {
        return yxInvestCartMapper.getYxStoreCartById(id);
    }


}
